package com.heima.user.service.ipml;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @author lzq
 * @data 2023/4/26 15:10
 */
@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    /**
     * app用户登录
     */
    public ResponseResult login(LoginDto dto) {
        /**
         * 1用户登录
         */
        //判断手机号好密码是否为空
        if (!StringUtils.isBlank(dto.getPhone())&&!StringUtils.isBlank(dto.getPassword())){
            //判断用户是否存在
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser==null){
                //用户不存在
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            //用户存在,判断密码是否一致
            String password = apUser.getPassword();
            String salt = apUser.getSalt();
            String pwd=dto.getPassword();
            String ps = DigestUtils.md5DigestAsHex((pwd + salt).getBytes());
            if (!ps.equals(password)){
                //密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //密码一致,返回对象和token
            HashMap<String, Object> map = new HashMap<>();
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            //对象信息中,密码和盐不返回
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("apUser",apUser);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }else {
            /**
             * 2游客登录
             */
            HashMap<String, Object> map = new HashMap<>();
            String token = AppJwtUtil.getToken(0L);
            //游客登陆返回token即可id为0
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
